import axios from 'axios'
import {Message, MessageBox} from 'element-ui'
//import store from '@/store'
import errorCode from '@/utils/errorCode'
import {parseParam, removeNullProps} from "@/utils/common";

let downloadLoadingInstance;

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: process.env.VUE_APP_BASE_API,
  // 超时
  timeout: 30000
})
// request拦截器
service.interceptors.request.use(config => {
  const url = config.url;
  if(config.method.toLowerCase() === 'get'){
    let spr = '?';
    if(url.indexOf('?') >= 0){
      spr = '&'
    }
    if(url.indexOf('_t=') === -1 ){
      config.url = url + spr + '_t=' + (new Date().getTime());
    }
    if(config.params){
      if(typeof(config.params) === 'string'){
        const allPath = config.url + '&' + config.params;
        config.url = allPath;
        config.params = null;
      }
    }
  }else if(config.method.toLowerCase() === 'post'){
    if(config.params){
      var urlParam = '';
      if(typeof(config.params) === 'string'){
        urlParam = config.params;
      }else if(Array.isArray(config.params)){
        urlParam = parseParam(config.params,'list')
      }else{
        urlParam = parseParam(config.params,null)
      }
      if(urlParam){
        let spr = '?';
        if(url.indexOf('?') >= 0){
          spr = '&'
        }
        config.url = url + spr + urlParam;
        config.params = null;
      }
    }
    if(config.data){
      //console.log(config.data);
      if(config.data instanceof FormData){
        //console.log(JSON.stringify(config.data));
      }else{
        const ppp = removeNullProps(config.data);
        if(ppp === null && Array.isArray(config.data)){
          config.data = [];
        }else{
          config.data = ppp;
        }
      }
    }
  }
  return config
}, error => {
    console.log(error)
    Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use(res => {
    // 未设置状态码则默认成功状态
    var status = Number(res.status) || 200;
    if(status == 200 && res.data && res.data.data && res.data.data.forbidType == 'timeout'){
      status = 401;
    }
    // 获取错误信息
    const msg = res.data.message || res.data.msg || errorCode[status] || errorCode["default"];
    // 二进制数据则直接返回
    if(res.request.responseType ===  'blob' || res.request.responseType ===  'arraybuffer'){
      return res.data
    }
    if (status === 401) {
      const isLoginPage = (location.href && location.href.indexOf("/login?")>0);
      if(!isLoginPage){
        MessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', {
            confirmButtonText: '重新登录',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          //store.dispatch('LogOut').then(() => {
            location.href = process.env.BASE_URL + 'index';
          //})
        })
      }else{
        Message({ showClose: true, message: '登录状态已过期，请重新登录', type: "error" });
      }
    } else if (status !== 200 || ( res.data.code !== "0000" && res.data.code !== 200 && res.data.code !== "0200"
    &&res.data.type != "application/x-download")) {
        Message({
            message: msg,
            type: "error"
        });
        return Promise.reject(new Error(msg));
    } else {
        if (res.data.data !== 'undefined') {
            return res.data.data;
        } else {
            return res.data;
        }
    }
  },
  error => {
    var toLogin = false;
    console.log('err' + error)
    let { message } = error;
    if (message == "Network Error") {
      message = "后端接口连接异常";
    }
    else if (message.includes("timeout")) {
      message = "系统接口请求超时";
    }
    else if (message.includes("Request failed with status code")) {
      let extMsg = "";
      if (error.response) {
        extMsg = ":" + JSON.stringify(error.response);

        if(error.response.status && error.response.status == 401){
          toLogin = true;
        }

        if (error.response.data) {
          var data = error.response.data.data;
          extMsg = ":" + JSON.stringify(error.response.data);
          if (error.response.data.message) {
              extMsg = ":" + JSON.stringify(error.response.data.message);
          }

          if(data && data.forbidType == 'timeout'){
            toLogin = true;
          }
        }
      }
      message = "系统接口" + message.substr(message.length - 3) + "异常" + extMsg;
    }

    if( toLogin ){
      MessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        //store.dispatch('LogOut').then(() => {
          location.href = process.env.BASE_URL + 'index';
        //})
      })
    }else{
      Message({
        message: message,
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(error)
    }
  }
)

// 通用下载方法
export function blobDownload(url, params, filename) {
  downloadLoadingInstance = Loading.service({ text: "正在下载数据，请稍候", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })
  return service.post(url, params, {
    transformRequest: [(params) => { return tansParams(params) }],
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    responseType: 'blob'
  }).then(async (data) => {
    const isLogin = await blobValidate(data);
    if (isLogin) {
      const blob = new Blob([data])
      saveAs(blob, filename)
    } else {
      const resText = await data.text();
      const rspObj = JSON.parse(resText);
      const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
      Message.error(errMsg);
    }
    downloadLoadingInstance.close();
  }).catch((r) => {
    console.error(r)
    Message.error('下载文件出现错误，请联系管理员！')
    downloadLoadingInstance.close();
  })
}

export default service
